import React from 'react'
import { Form, Button, InputNumber } from 'antd'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { submitQuizItemAnswer } from '../../actions/tws-logic-quiz-submission'
import { get } from 'lodash'
import {UPDATE_LOGIC_QUIZ_ITEM_ANSWERS} from '../../constant/action-type'

const FormItem = Form.Item

class QuizDescription extends React.Component {
  handleSubmit (e) {
    e.preventDefault()

    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return
      }
      const {history, match, quizItemId, isExample} = this.props
      const {programId, taskId, assignmentId, quizId, quizItemOrderNum} = match.params

      if (!isExample) {
        this.props.submitQuizItemAnswer({
          assignmentId,
          'answers': [
            {quizItemId, answer: fieldsValue.answer}
          ]
        })
      }

      if (!this.hasNext()) {
        return
      }

      const num = parseInt(quizItemOrderNum, 10) + 1
      const uri = `/student/program/${programId}/task/${taskId}/assignments/${assignmentId}/logic-quizzes/${quizId}/quiz-items/${num}`

      history.push(uri)
    })
  }

  hasNext () {
    const count = get(this.props, 'logicQuizSubmission.twlogicQuizItemAnswer.length', 0)
    const current = get(this.props, 'match.params.quizItemOrderNum', 0)

    return parseInt(current, 10) < count
  }

  getButtonText () {
    const {isExample} = this.props
    if (isExample) {
      return '查看下一题'
    }
    return this.hasNext() ? '提交并进入下一题' : '提交并返回'
  }

  isTimeOver () {
    const {restTimeInSeconds, reviewQuiz} = this.props
    return restTimeInSeconds < 0 || reviewQuiz.id
  }

  handleAnswerChange (answer) {
    const {quizItemId} = this.props
    this.props.updateLogicQuizItemAnswer({answer, quizItemId})
    return answer
  }
  render () {
    const {questionZh, form} = this.props
    const {getFieldDecorator} = form
    const timeOver = this.isTimeOver()
    let buttonText = this.getButtonText()

    return (
      <div>
        <div style={{lineHeight: '4'}}>{questionZh}</div>
        <Form layout='inline' onSubmit={this.handleSubmit.bind(this)}>
          <FormItem />
          <FormItem>
            {getFieldDecorator('answer', {
              rules: [{required: true, message: '答案不能为空'}],
              getValueFromEvent: this.handleAnswerChange.bind(this)

            })(<InputNumber
              disabled={this.props.isExample || timeOver}
              placeholder='请输入答案' style={{width: 100}} />)}
          </FormItem>
          <FormItem>
            <Button
              type='primary'
              htmlType='submit'
              disabled={timeOver}
              >
              {buttonText}
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapPropsToFields = ({answer, exampleAnswer}) => {
  return {
    answer: Form.createFormField({
      value: exampleAnswer || answer
    })
  }
}

const mapStateToProps = ({logicQuizSubmission, logicQuizItem, restTimeInSeconds, reviewQuiz}) => ({
  logicQuizSubmission,
  isExample: logicQuizItem.isExample,
  exampleAnswer: logicQuizItem.exampleAnswer,
  restTimeInSeconds,
  reviewQuiz
})

const mapDispatchToProps = dispatch => ({
  submitQuizItemAnswer: async param => dispatch(await submitQuizItemAnswer(param)),
  updateLogicQuizItemAnswer: param => dispatch({type: UPDATE_LOGIC_QUIZ_ITEM_ANSWERS, data: param})

})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create({mapPropsToFields})(QuizDescription)))
